package com.autonavi.yunda.yunji.common.utils;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.taobao.vipserver.client.core.Host;
import com.taobao.vipserver.client.core.VIPClient;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class VipServerUtil {
    /**
     * 从url中获取vipserver域名，并通过VIPClient客户端解析为具体ip
     */
    public static String getVipUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            String vipHost = getVipHost(url.getHost());
            return url.getProtocol() + "://" + vipHost + url.getFile();
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "解析vipserver url失败,url:" + urlString, e);
        }
    }

    public static String getVipHost(String host) {
        Host vipHost;
        try {
            vipHost = VIPClient.srvHost(host);
            return vipHost.toInetAddr();
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "解析vipserver host失败,host:" + host, e);
        }
    }

    public static List<String> listVipHosts(String host) {
        try {
            List<Host> hosts = VIPClient.srvHosts(host);
            return hosts.stream().map(Host::toInetAddr).collect(Collectors.toList());
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "解析vipserver host失败,host:" + host, e);
        }
    }


}
